/***
 * 调用此类要注释CartConsumerApplication类的 @LoadBalanced 注解
 * --不能重复开启@LoadBalanced负载均衡，否则销费者端找不到相应的服务
 * 类LoadBalanced 与 LoadBalancerClient 不能重复使用；
 */
package com.gan.springcloud.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AccountController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;//负载均衡客户端
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/getAccount", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getAccount() {
        Map<String,Object> account = new HashMap<>();
        System.out.println("---------消费者开始------------");
        //用负载均衡客户端调用服务--获取注册中心的已经注册的服务
        ServiceInstance serviceInstance = loadBalancerClient.choose("goods-provider");
        //根据服务获取相应URL地址；
        String url = String.format("http://%s:%s/getAccount", serviceInstance.getHost(), serviceInstance.getPort());
        System.out.println("request url:"+url);
        account = restTemplate.getForObject(url, HashMap.class);//凋用服务;
        System.out.println("---------消费者结束--------account{}----:" + account);
        return account;
    }
}
